<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use app\common\service\Activity;
use think\Config;
use think\Cookie;
use think\Db;
use think\Hook;
use think\Session;
use think\Validate;

/**
 * 会员中心
 */
class User extends Frontend
{
    protected $layout = 'default';
    protected $noNeedLogin = ['login', 'register', 'third','test'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $auth = $this->auth;

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

        //监听注册登录注销的事件
        Hook::add('user_login_successed', function ($user) use ($auth) {
            $expire = input('post.keeplogin') ? 30 * 86400 : 0;
            Cookie::set('uid', $user->id, $expire);
            Cookie::set('token', $auth->getToken(), $expire);
        });
        Hook::add('user_register_successed', function ($user) use ($auth) {
            Cookie::set('uid', $user->id);
            Cookie::set('token', $auth->getToken());
        });
        Hook::add('user_delete_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
        Hook::add('user_logout_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
    }

    /**
     * 空的请求
     * @param $name
     * @return mixed
     * @throws \think\Exception
     */
    public function _empty($name)
    {
        $data = Hook::listen("user_request_empty", $name);
        foreach ($data as $index => $datum) {
            $this->view->assign($datum);
        }
        return $this->view->fetch('user/' . $name);
    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->view->assign('title', __('User center'));
        return $this->view->fetch();
    }

    public function test() {
        return $this->view->fetch();
    }

    /**
     * 注册会员
     * @throws \Exception
     */
    public function register()
    {
        $url = $this->request->request('url', '', 'trim');
        if ($this->auth->id) {
            $this->success(__('You\'ve logged in, do not login again'), $url ? $url : url('user/index'));
        }
        if ($this->request->isPost()) {
            $username = $this->request->post('username');
            $password = $this->request->post('password');
            $email = $this->request->post('email','');
            $mobile = $this->request->post('mobile', '');
            $tjr_username = $this->request->post('tjr_username', '');
            $captcha = $this->request->post('captcha');
            $token = $this->request->post('__token__');
            $rule = [
                'username'  => 'require|length:3,30',
                'password'  => 'require|length:6,30',
                //'email'     => 'require|email',
                'mobile'    => 'regex:/^1\d{10}$/',
                //'captcha'   => 'require|captcha',
                //'__token__' => 'require|token',
            ];

            $msg = [
                'username.require' => 'Username can not be empty',
                'username.length'  => 'Username must be 3 to 30 characters',
                'password.require' => 'Password can not be empty',
                'password.length'  => 'Password must be 6 to 30 characters',
                //'captcha.require'  => 'Captcha can not be empty',
                //'captcha.captcha'  => 'Captcha is incorrect',
                //'email'            => 'Email is incorrect',
                'mobile'           => 'Mobile is incorrect',
            ];
            $data = [
                'username'  => $username,
                'password'  => $password,
                'email'     => $email,
                'mobile'    => $mobile,
                //'captcha'   => $captcha,
                //'__token__' => $token,
            ];
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
            }
            if ($this->auth->register($username, $password, $email, $mobile,$tjr_username)) {
                $this->success(__('Sign up successful'), $url ? $url : url('user/index'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        //判断来源
        $referer = $this->request->server('HTTP_REFERER');
        if (!$url && (strtolower(parse_url($referer, PHP_URL_HOST)) == strtolower($this->request->host()))
            && !preg_match("/(user\/login|user\/register|user\/logout)/i", $referer)) {
            $url = $referer;
        }
        $this->view->assign('url', $url);
        $this->view->assign('title', __('Register'));
        return $this->view->fetch();
    }

    /**
     * 会员登录
     */
    public function login()
    {
        $url = $this->request->request('url', '', 'trim');
        if ($this->auth->id) {
            $this->success(__('You\'ve logged in, do not login again'), $url ? $url : url('user/index'));
        }
        if ($this->request->isPost()) {
            $account = $this->request->post('account');
            $password = $this->request->post('password');
            $keeplogin = (int)$this->request->post('keeplogin');
            $token = $this->request->post('__token__');
            $rule = [
                'account'   => 'require|length:3,50',
                'password'  => 'require|length:6,30',
                '__token__' => 'require|token',
            ];

            $msg = [
                'account.require'  => 'Account can not be empty',
                'account.length'   => 'Account must be 3 to 50 characters',
                'password.require' => 'Password can not be empty',
                'password.length'  => 'Password must be 6 to 30 characters',
            ];
            $data = [
                'account'   => $account,
                'password'  => $password,
                '__token__' => $token,
            ];
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
                return false;
            }
            if ($this->auth->login($account, $password)) {
                $this->success(__('Logged in successful'), $url ? $url : url('user/index'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        //判断来源
        $referer = $this->request->server('HTTP_REFERER');
        if (!$url && (strtolower(parse_url($referer, PHP_URL_HOST)) == strtolower($this->request->host()))
            && !preg_match("/(user\/login|user\/register|user\/logout)/i", $referer)) {
            $url = $referer;
        }
        $this->view->assign('url', $url);
        $this->view->assign('title', __('Login'));
        return $this->view->fetch();
    }

    /**
     * 注销登录
     */
    public function logout()
    {
        //注销本站
        $this->auth->logout();
        $this->success(__('Logout successful'), url('user/index'));
    }

    /**
     * 个人信息
     */
    public function profile()
    {
        $this->view->assign('title', __('Profile'));
        return $this->view->fetch();
    }


    /**
     * 我的团队
     * @return string
     * @throws \think\Exception
     */
    public function team()
    {
        //生成更新团队数据
        Activity::updateTeamList($this->auth->username,$this->auth->id);
        $params = $this->request->param();
        //展示团队列表
        $where = ['current_user_id'=>$this->auth->id];
        //亲密度搜索
        if (isset($params['qin_mi']) && in_array($params['qin_mi'],[1,2,3])) {
            $where['qin_mi'] = intval($params['qin_mi']);
        }
        //用户名搜索
        if (isset($params['search_user']) && !empty($params['search_user'])) {
            $search = addslashes($params['search_user']);
            $where['username'] = ['like','%'.$search.'%'];
        }
        $list = Db::name('activity_temp_team')->where($where)->order('qin_mi ASC')->paginate(8);
        $list->appends($params);

        $this->view->assign('list', $list);
        $this->view->assign('total', $list->total());
        $this->view->assign('page', $list->render());
        return $this->view->fetch();
    }

    //推荐网体
    public function tree()
    {
        $search = $this->request->param('search');
        if(!empty($search)){
            $firstUser = Db::name('user')->where(['username'=>$search])->find();
            if(empty($firstUser)) {
                $this->error("查询会员不存在！");
            }
        }else{
            $firstUser = Db::name('user')->order('id asc')->find();
        }

        $users = getTreeDownUser($firstUser['username'],1,3,[]);
        $this->assign("firstUserInfo",$firstUser);
        $this->assign('users',$users);
        return $this->view->fetch();
    }


    /**
     * 修改推荐关系
     * @return string
     * @throws \think\Exception
     */
    public function editTree()
    {
        if ($this->request->isPost()) {
            $model = Db::name("user");
            $username = $this->request->post('username','','trim');
            $new_tjr  = $this->request->post('new_tjr','','trim');
            if(empty($username)) $this->error("请输入会员账号");
            if(empty($new_tjr))  $this->error("请输入新邀请码");
            if(strtolower($username) == strtolower($new_tjr)) $this->error("新邀请码不能是自己!");
            $rsu = $model->where(['username'=>$username])->find();
            if(!$rsu) $this->error("会员帐号 ".$username .' 不存在！ ');

            $rst = $model->where(['username'=>$new_tjr])->find();
            if(!$rst) $this->error("新邀请码 ".$new_tjr .' 不存在！ ');

            if(strtolower($rsu['tjr_username']) == strtolower($new_tjr)) $this->error("新邀请码不能是原来的邀请码!");
            //互为上级的判断
            if ($rst['tjr_username'] == $username) $this->error('两人不能互为上级');

            $data = [];
            if($rst['tjr_string']) {
                $tj_ary = explode(',',$rst['tjr_string']);
                if(in_array($rsu['id'],$tj_ary)) {
                    $this->error("新邀请码不能是自己网体下级会员！");
                }
                $data['tjr_string'] = $rst['tjr_string'].','.$rst['id'];
            }
            else {
                $data['tjr_string'] = $rst['id'];
            }
            //更新被移动网体的会员
            Db::startTrans();
            $data['ceng_num'] = $rst['ceng_num']+1;
            $data['tjr_username'] = $new_tjr;
            $data['tjr_uid'] = $rst['id'];
            $rs = $model->where(['username'=>$username])->update($data);
            if($rs ===false) {
                Db::rollback();
                $this->error("移动网体失败");
            }
            //更新移动网体的会员的下级会员
            $rsu_id  = $rsu['id'];
            $down_all = $model->where(" find_in_set('$rsu_id',tjr_string)>0 ")->field('id,username,ceng_num,tjr_username')->order("ceng_num asc")->select();
            //新的层数差
            $num_diff = $rst['ceng_num']-$rsu['ceng_num']+1;
            foreach($down_all as $key=>$users) {
                $newData = array();
                $newData['ceng_num'] = $users['ceng_num']+$num_diff;
                //重新更新推荐人信息
                $rs_tjr = $model->where(['username'=>$users['tjr_username']])->field('id,username,tjr_string')->find();
                $newData['tjr_string']  = $rs_tjr['tjr_string'].','.$rs_tjr['id'];
                $rs = $model->where(array('id'=>$users['id']))->update($newData);
                if($rs === false) {
                    Db::rollback();
                    $this->error("移动网体失败！");
                }
            }

            $team = count($down_all)+1;
            //被更新用户的推荐人直推数减1，团队数减team。同理，新推荐人直推数加1，团队数加team。共同上级先减后加则没有变化
            updateTeamNumber($rsu['tjr_username'],-1,-$team);
            updateTeamNumber($new_tjr,1,$team);
            Db::commit();
            $this->success('推荐人更新成功');
        }
        return $this->view->fetch();
    }
    /**
     * 修改密码
     */
    public function changepwd()
    {
        if ($this->request->isPost()) {
            $oldpassword = $this->request->post("oldpassword");
            $newpassword = $this->request->post("newpassword");
            $renewpassword = $this->request->post("renewpassword");
            $token = $this->request->post('__token__');
            $rule = [
                'oldpassword'   => 'require|length:6,30',
                'newpassword'   => 'require|length:6,30',
                'renewpassword' => 'require|length:6,30|confirm:newpassword',
                '__token__'     => 'token',
            ];

            $msg = [
            ];
            $data = [
                'oldpassword'   => $oldpassword,
                'newpassword'   => $newpassword,
                'renewpassword' => $renewpassword,
                '__token__'     => $token,
            ];
            $field = [
                'oldpassword'   => __('Old password'),
                'newpassword'   => __('New password'),
                'renewpassword' => __('Renew password')
            ];
            $validate = new Validate($rule, $msg, $field);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
                return false;
            }

            $ret = $this->auth->changepwd($newpassword, $oldpassword);
            if ($ret) {
                $this->success(__('Reset password successful'), url('user/login'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        $this->view->assign('title', __('Change password'));
        return $this->view->fetch();
    }
}
